﻿using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using net.xBei.WebApi.Repository;
using xBei.Redis.Extension;

namespace net.xBei.WebApi {
    public partial class WebApplication {
        private static bool HasHealthCheck;
        /// <summary>
        /// 配置健康监测
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IServiceCollection SetupHealthCheck(this IServiceCollection services, Action<IHealthChecksBuilder> builder) {
            var healthCheck = services.AddSingleton<RedisHealthCheck>()
                                      .AddHealthChecks()
                                      .AddCheck<ReadyHealthCheck>("Ready", tags: new[] { "ready" });
            builder.Invoke(healthCheck);
            HasHealthCheck = true;
            return services;
        }
        /// <summary>
        /// 配置Redis健康监测
        /// </summary>
        /// <param name="builder"></param>
        public static IHealthChecksBuilder AddRedisCheck(this IHealthChecksBuilder builder) {
            return builder.AddCheck<RedisHealthCheck>("Redis", tags: new[] { "ready", "alive" });
        }
        /// <summary>
        /// 事件服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="setupAction"></param>
        public static IServiceCollection SetupEvents(this IServiceCollection services, Action? setupAction = null) {
            services.AddSingleton<EventService>();
            setupAction?.Invoke();
            return services;
        }
        /// <summary>
        /// 配置数据类自动映射。<see cref="xBei.Models.AutoMapProfile"/>
        /// </summary>
        /// <typeparam name="TMapProfile"></typeparam>
        /// <param name="services"></param>
        public static IServiceCollection SetupAutoMapper<TMapProfile>(this IServiceCollection services) where TMapProfile : xBei.Models.AutoMapProfile
            => services.AddAutoMapper(typeof(TMapProfile));
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        /// <param name="ConfigSectionName">配置节点名称</param>
        /// <param name="ConfigKey"></param>
        public static IServiceCollection SetupDatabase<TContext>(this IServiceCollection services,
                                                   IConfiguration Configuration,
                                                   string ConfigSectionName,
                                                   string ConfigKey) where TContext : DbContext {
            return services.AddDbContextPool<TContext>(o =>
              o.UseMySql(Configuration.GetSection(ConfigSectionName)[ConfigKey],
                         ServerVersion.AutoDetect(Configuration.GetSection(ConfigSectionName)[ConfigKey]),
                         mySqlOptionsAction => {
                             mySqlOptionsAction.EnableStringComparisonTranslations(true);
                             mySqlOptionsAction.EnableIndexOptimizedBooleanColumns(true);
                             // mySqlOptionsAction.EnableRetryOnFailure();
                         })
                .EnableSensitiveDataLogging()
                .EnableDetailedErrors()
            );
        }

        /// <summary>
        /// 配置Redis
        /// </summary>
        /// <typeparam name="TSettings"></typeparam>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="settingKey"></param>
        public static IServiceCollection SetupRedis<TSettings>(this IServiceCollection services, IConfigurationRoot configuration, string settingKey)
            where TSettings : RedisSettings {
            services.Configure<TSettings>(configuration.GetSection(settingKey));
            services.AddSingleton<RedisClient>();
            return services;
        }
        /// <summary>
        /// 配置Robots.txt
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder SetupRobots(this IApplicationBuilder app) {
            app.UseEndpoints(configure => {
                configure.MapGet("/robots.txt", async context => {
                    context.Response.ContentType = "text/plain";
                    await context.Response.WriteAsync("User-agent: *\nDisallow: /");
                });
            });
            return app;
        }
    }
}
